#include "VisualizeNode2D.hpp"
#include <Renderer/Vis2DRenderer.hpp>
#include <Resource/Shader/Shader.hpp>
#include <Graphics/ColorDefine.hpp>

namespace zzz{
VisualizeNode2D::~VisualizeNode2D()
{
  Clear();
}

void VisualizeNode2D::Clear()
{
  for (size_t i=0; i<objs_.size(); i++)
    delete objs_[i];
  objs_.clear();
}

void VisualizeNode2D::DrawPixels(Vis2DRenderer *renderer)
{
  CHECK_GL_ERROR();
  for (size_t i=0; i<objs_.size(); i++)
    objs_[i]->DrawPixels(renderer, posx_, posy_);
  CHECK_GL_ERROR();

  if (drawedge_)
  {
    Vector3d x1=renderer->UnProject(bbox_.Min(0)+posx_,bbox_.Min(1)+posy_);
    Vector3d y1=renderer->UnProject(bbox_.Min(0)+posx_,bbox_.Max(1)+posy_);
    Vector3d x2=renderer->UnProject(bbox_.Max(0)+posx_,bbox_.Max(1)+posy_);
    Vector3d y2=renderer->UnProject(bbox_.Max(0)+posx_,bbox_.Min(1)+posy_);
    Vector3d x3=renderer->UnProject(bbox_.Min(0)+posx_,bbox_.Min(1)+posy_);

    ColorDefine::white.ApplyGL();
    ZRM->Get<Shader*>("ColorShader")->Begin();
    glBegin(GL_LINES);
    glVertex3dv(x1.Data());
    glVertex3dv(y1.Data());
    glVertex3dv(x2.Data());
    glVertex3dv(y1.Data());
    glVertex3dv(x2.Data());
    glVertex3dv(y2.Data());
    glVertex3dv(x3.Data());
    glVertex3dv(y2.Data());
    glEnd();
    Shader::End();
  }
}

void VisualizeNode2D::AddObject(VisualizeObj2D* obj)
{
  if (objs_.empty())
    bbox_=obj->bbox_;
  else
    bbox_+=obj->bbox_;
  objs_.push_back(obj);
}
}